import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import "./plugins/element.js";
import "reset-css";
import axios from "axios";
import "./assets/fonts/iconfont.css";
import store from "./store/index.js";
import TreeTable from "vue-table-with-tree-grid";
import DkTable from "@/comp/DkTable";
import DkQuery from "@/comp/DkQuery";
import DeleteMessageBox from "@/comp/DeleteMessageBox";
import BreadCrumbs from "@/components/BreadCrumbs";

import common from "@/mixins/common";
import { Message } from "element-ui";

// 导入NProgress 对应的js和css
import NProgress from "nprogress";
import "nprogress/nprogress.css";

Vue.config.productionTip = false;
// 配置请求的根路径
// axios.defaults.baseURL = 'http://8.134.250.251:3000'
// axios.defaults.baseURL = process.env.VUE_APP_BASE_URL + '/api'

// 在开发环境中，我们不设置 `baseUrl`，使用 webpack-dev-server 的代理
// if (process.env.NODE_ENV !== 'development') {
//   axios.defaults.baseURL = process.env.VUE_APP_BASE_URL;
//   // 在生产环境中，我们设置 `baseUrl` 为我们的生产服务器的地址
// }
axios.defaults.withCredentials = true;
// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    NProgress.start();
    return config;
  },
  (error) => {
    Message.error(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use((config) => {
  if (config.data.code === 401) {
    Message.error("登录过期，请重新登录");
    localStorage.removeItem("token");
    router.push("/login");
  }
  NProgress.done()
  return config.data 
});

Vue.mixin(common);

Vue.prototype.$http = axios;
Vue.prototype.deleteMessageBox = DeleteMessageBox;

Vue.component("tree-table", TreeTable);
Vue.component("DkTable", DkTable);
Vue.component("DkQuery", DkQuery);
Vue.component("BreadCrumbs", BreadCrumbs);

//全局时间过滤器，用在List.vue的毫秒转换时间
Vue.filter("dateFormat", function (originVal) {
  const dt = new Date(originVal);
  const y = dt.getFullYear();
  // padStart 2位，不足2位用0填充
  const m = (dt.getMonth() + 1 + "").padStart(2, "0");
  const d = (dt.getDate() + "").padStart(2, "0");

  const hh = (dt.getHours() + "").padStart(2, "0");
  const mm = (dt.getMinutes() + "").padStart(2, "0");
  const ss = (dt.getSeconds() + "").padStart(2, "0");

  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
});

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");
